<template>
  <view class="review-container">
    <!-- 头部区域 -->
    <view class="header">
      <text class="title">内容审核</text>
    </view>

    <!-- 筛选区域 -->
    <view class="filter-section">
      <view class="filter-row">
        <view
          v-for="(tab, index) in tabs"
          :key="index"
          :class="['tab-item', activeTab === tab.value ? 'tab-item-active' : '']"
          @tap="activeTab = tab.value"
        >
          {{ tab.label }}
          <text class="badge" v-if="tab.count > 0">{{ tab.count }}</text>
        </view>
      </view>
    </view>

    <!-- 内容列表 -->
    <view class="content-list">
      <!-- 加载中提示 -->
      <view class="loading-container" v-if="loading">
        <view class="loading-spinner"></view>
        <text class="loading-text">加载中...</text>
      </view>

      <!-- 动态内容 -->
      <view
        class="content-item"
        v-for="(item, index) in filteredContents"
        :key="index"
        v-else-if="filteredContents.length > 0"
      >
        <view class="item-header">
          <view class="user-info">
            <image
              class="avatar"
              :src="item.avatar || '/static/images/default-avatar.png'"
              mode="aspectFill"
            />
            <view class="user-details">
              <text class="username">{{ item.username }}</text>
              <text class="time">{{ item.createdTime }}</text>
            </view>
          </view>
          <text class="content-tag" :class="getTagClass(item.type)">{{ item.type }}</text>
        </view>

        <view class="item-content">
          <text class="content-text">{{ item.content }}</text>
          <view class="image-container" v-if="getImages(item).length > 0">
            <image
              v-for="(img, imgIndex) in getImages(item)"
              :key="imgIndex"
              :src="getImageUrl(img)"
              mode="aspectFill"
              class="content-image"
              @tap="previewImage(getImages(item), imgIndex)"
            />
          </view>
        </view>

        <view class="item-footer">
          <view class="report-reason" v-if="item.reportReason">
            <text class="reason-label">举报理由：</text>
            <text class="reason-text">{{ item.reportReason }}</text>
            <text class="reports-count">{{ item.reportsCount || 1 }}人举报</text>
          </view>

          <view class="review-actions" v-if="activeTab === 'pending'">
            <button class="action-button approve" @tap="approveContent(item.id)">通过</button>
            <button class="action-button reject" @tap="showRejectModal(item)">拒绝</button>
            <button
              class="action-button ignore"
              @tap="ignoreReport(item.id)"
              v-if="activeTab === 'reported'"
            >
              忽略举报
            </button>
          </view>
        </view>
      </view>

      <!-- 空状态提示 -->
      <view class="empty-list" v-else>
        <image class="empty-icon" src="/static/images/empty.png" mode="aspectFit" />
        <text class="empty-text">暂无{{ getTabLabel(activeTab) }}内容</text>
        <text class="empty-description" v-if="activeTab === 'pending'">当前没有需要审核的内容</text>
      </view>
    </view>
  </view>
</template>

<script lang="ts">
import { defineComponent } from 'vue'
import { findAllDeniedPosts, approvePost, findRejectedPosts, rejectPost } from '@/api/my'

interface PostDto {
  id: number
  userId: number
  content: string
  createdTime: string
  likeCount: number
  commentCount: number
  favoriteCount: number
  images?: string[]
  type?: string
  username?: string
  userAvatar?: string
  status?: string
  reportReason?: string
  reportsCount?: number
}

interface TabItem {
  label: string
  value: string
  count: number
}

interface ApiResponse<T> {
  code: number
  info: string
  data: T
}

export default defineComponent({
  data() {
    return {
      activeTab: 'pending',
      currentRejectItem: null as PostDto | null,
      tabs: [
        { label: '待审核', value: 'pending', count: 0 },
        { label: '已举报', value: 'reported', count: 0 },
        { label: '已通过', value: 'approved', count: 0 },
        { label: '已拒绝', value: 'rejected', count: 0 },
      ] as TabItem[],
      pendingPosts: [] as PostDto[],
      rejectedPosts: [] as PostDto[],
      loading: false,
    }
  },

  computed: {
    filteredContents(): PostDto[] {
      switch (this.activeTab) {
        case 'pending':
          return this.pendingPosts
        case 'rejected':
          return this.rejectedPosts
        default:
          return []
      }
    },
  },

  methods: {
    getTabLabel(value: string): string {
      const tab = this.tabs.find((t) => t.value === value)
      return tab ? tab.label : ''
    },

    getTagClass(type: string): string {
      switch (type) {
        case '动态':
          return 'tag-post'
        case '评论':
          return 'tag-comment'
        case '回复':
          return 'tag-reply'
        default:
          return 'tag-post' // 默认显示为动态
      }
    },

    previewImage(images: string[], currentIndex: number) {
      const urls = images.map((img) => this.getImageUrl(img))
      uni.previewImage({
        urls: urls,
        current: urls[currentIndex],
      })
    },

    getImages(item: any): string[] {
      if (!item) return []

      // 处理图片数据可能是字符串的情况
      if (typeof item.images === 'string') {
        try {
          // 尝试解析JSON字符串
          const parsed = JSON.parse(item.images)
          if (Array.isArray(parsed)) {
            return parsed // 如果是数组直接返回
          } else if (typeof parsed === 'string') {
            return [parsed] // 如果是单个字符串URL，放入数组返回
          } else if (parsed && typeof parsed === 'object') {
            // 如果是对象，尝试提取URL字段
            const urls = Object.values(parsed).filter((v) => typeof v === 'string')
            return urls.length ? (urls as string[]) : []
          }
        } catch (e) {
          // 如果解析失败，可能是单个URL字符串
          console.log('解析图片数据失败', e)
          return [item.images] // 当作单个URL处理
        }
      }

      // 如果已经是数组直接返回
      if (Array.isArray(item.images)) {
        return item.images
      }

      // 检查是否有image单数字段
      if (item.image) {
        return typeof item.image === 'string' ? [item.image] : []
      }

      return []
    },

    getImageUrl(img: string | any): string {
      if (!img) return ''

      // 如果是字符串，可能是URL或路径
      if (typeof img === 'string') {
        // 如果是完整URL，直接返回
        if (img.startsWith('http://') || img.startsWith('https://')) {
          return img
        }
        // 如果是相对路径，需要添加基础URL
        if (img.startsWith('/')) {
          return import.meta.env.VITE_API_BASE_URL + img
        }
        // 否则作为完整路径返回
        return img
      }

      // 如果是对象，尝试获取url字段
      if (typeof img === 'object' && img !== null) {
        return img.url || img.path || ''
      }

      return ''
    },

    async fetchDeniedPosts() {
      this.loading = true
      uni.showLoading({
        title: '加载中...',
      })

      try {
        const res = await findAllDeniedPosts()
        if (res.statusCode === 200 && res.data) {
          const responseData = res.data as ApiResponse<PostDto[]>
          if (responseData.code === 200) {
            // 处理返回的数据
            this.pendingPosts = (responseData.data || []).map((post) => {
              console.log('待审核帖子数据:', post) // 添加日志以便调试

              // 为每个帖子添加状态
              return {
                ...post,
                status: 'pending',
                type: '动态', // 默认类型为动态
              }
            })

            // 更新tab数量
            this.updateTabCounts()
          } else {
            uni.showToast({
              title: responseData.info || '获取数据失败',
              icon: 'none',
            })
          }
        }
      } catch (error) {
        console.error('获取待审核内容失败:', error)
        uni.showToast({
          title: '获取数据失败',
          icon: 'none',
        })
      } finally {
        uni.hideLoading()
        this.loading = false
      }
    },

    async fetchRejectedPosts() {
      this.loading = true
      uni.showLoading({
        title: '加载中...',
      })

      try {
        const res = await findRejectedPosts()
        if (res.statusCode === 200 && res.data) {
          const responseData = res.data as ApiResponse<PostDto[]>
          if (responseData.code === 200) {
            // 处理返回的数据
            this.rejectedPosts = (responseData.data || []).map((post) => {
              console.log('已拒绝帖子数据:', post) // 添加日志以便调试

              // 为每个帖子添加状态
              return {
                ...post,
                status: 'rejected',
                type: '动态', // 默认类型为动态
              }
            })

            // 更新tab数量
            this.updateTabCounts()
          } else {
            uni.showToast({
              title: responseData.info || '获取数据失败',
              icon: 'none',
            })
          }
        }
      } catch (error) {
        console.error('获取已拒绝内容失败:', error)
        uni.showToast({
          title: '获取数据失败',
          icon: 'none',
        })
      } finally {
        uni.hideLoading()
        this.loading = false
      }
    },

    approveContent(id: number) {
      uni.showModal({
        title: '审核确认',
        content: '确定通过此内容？',
        success: (res) => {
          if (res.confirm) {
            uni.showLoading({
              title: '处理中...',
            })

            approvePost(id)
              .then((res) => {
                uni.hideLoading()

                if (res.statusCode === 200 && res.data) {
                  const responseData = res.data as ApiResponse<any>
                  if (responseData.code === 200) {
                    // 更新本地状态
                    const contentIndex = this.pendingPosts.findIndex((item) => item.id === id)
                    if (contentIndex !== -1) {
                      // 从待审核列表移除
                      this.pendingPosts.splice(contentIndex, 1)
                      // 更新标签计数
                      this.updateTabCounts()
                    }

                    uni.showToast({
                      title: '已通过',
                      icon: 'success',
                    })
                  } else {
                    uni.showToast({
                      title: responseData.info || '操作失败',
                      icon: 'none',
                    })
                  }
                } else {
                  uni.showToast({
                    title: '操作失败',
                    icon: 'none',
                  })
                }
              })
              .catch((error) => {
                uni.hideLoading()
                console.error('审核通过请求错误:', error)
                uni.showToast({
                  title: '操作失败',
                  icon: 'none',
                })
              })
          }
        },
      })
    },

    showRejectModal(item: PostDto) {
      this.currentRejectItem = item
      uni.showModal({
        title: '拒绝确认',
        content: '确定拒绝此内容？',
        success: (res) => {
          if (res.confirm) {
            this.confirmReject()
          }
        },
      })
    },

    closeRejectModal() {
      this.currentRejectItem = null
    },

    confirmReject() {
      if (!this.currentRejectItem) return

      uni.showLoading({
        title: '处理中...',
      })

      rejectPost(this.currentRejectItem.id)
        .then((res) => {
          if (res.statusCode === 200 && res.data) {
            const responseData = res.data as ApiResponse<any>
            if (responseData.code === 200) {
              // 从列表中移除
              const contentIndex = this.pendingPosts.findIndex(
                (item) => item.id === this.currentRejectItem?.id,
              )
              if (contentIndex !== -1) {
                this.pendingPosts.splice(contentIndex, 1)

                // 更新标签计数
                this.updateTabCounts()
              }

              uni.showToast({
                title: '已拒绝',
                icon: 'success',
              })
            } else {
              uni.showToast({
                title: responseData.info || '操作失败',
                icon: 'none',
              })
            }
          } else {
            uni.showToast({
              title: '操作失败',
              icon: 'none',
            })
          }
        })
        .catch((error) => {
          console.error('拒绝请求错误:', error)
          uni.showToast({
            title: '操作失败',
            icon: 'none',
          })
        })
        .finally(() => {
          uni.hideLoading()
          this.closeRejectModal()
        })
    },

    ignoreReport(id: number) {
      uni.showModal({
        title: '确认操作',
        content: '确定忽略此举报？',
        success: (res) => {
          if (res.confirm) {
            // TODO: 调用后端API忽略举报
            uni.showLoading({
              title: '处理中...',
            })

            setTimeout(() => {
              uni.hideLoading()

              // 从列表中移除
              const contentIndex = this.pendingPosts.findIndex((item) => item.id === id)
              if (contentIndex !== -1) {
                this.pendingPosts.splice(contentIndex, 1)

                // 更新标签计数
                this.updateTabCounts()
              }

              uni.showToast({
                title: '已忽略举报',
                icon: 'success',
              })
            }, 1000)
          }
        },
      })
    },

    updateTabCounts() {
      // 更新待审核标签的数量
      const pendingTab = this.tabs.find((tab) => tab.value === 'pending')
      if (pendingTab) {
        pendingTab.count = this.pendingPosts.length
      }

      // 更新已拒绝标签的数量
      const rejectedTab = this.tabs.find((tab) => tab.value === 'rejected')
      if (rejectedTab) {
        rejectedTab.count = this.rejectedPosts.length
      }
    },

    fetchContents() {
      // 获取待审核内容
      this.fetchDeniedPosts()

      // 获取已拒绝内容
      this.fetchRejectedPosts()
    },
  },

  onLoad() {
    this.fetchContents()
  },

  onShow() {
    // 每次显示页面时都重新获取数据
    this.fetchContents()
  },
})
</script>

<style lang="scss">
// 薰衣草紫主题色
$theme-color: #9370db;
$light-theme-color: #e6e6fa;
$text-color: #333333;
$border-color: #eeeeee;
$success-color: #52c41a;
$warning-color: #faad14;
$danger-color: #ff6b6b;

.review-container {
  min-height: 100vh;
  background-color: #f8f8f8;

  .header {
    background: linear-gradient(180deg, $theme-color 0%, $light-theme-color 100%);
    padding: 40rpx 30rpx;

    .title {
      font-size: 36rpx;
      font-weight: bold;
      color: #ffffff;
    }
  }

  .filter-section {
    background-color: #ffffff;
    padding: 20rpx;
    margin-bottom: 20rpx;
    box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.05);
    position: sticky;
    top: 0;
    z-index: 10;

    .filter-row {
      display: flex;
      justify-content: space-around;
      align-items: center;

      .tab-item {
        position: relative;
        padding: 16rpx 24rpx;
        font-size: 28rpx;
        color: #666666;
        border-radius: 8rpx;

        &-active {
          color: $theme-color;
          font-weight: 500;
          background-color: $light-theme-color;
        }

        .badge {
          position: absolute;
          top: -6rpx;
          right: -6rpx;
          background-color: $danger-color;
          color: #ffffff;
          font-size: 20rpx;
          min-width: 32rpx;
          height: 32rpx;
          line-height: 32rpx;
          text-align: center;
          border-radius: 16rpx;
          padding: 0 6rpx;
        }
      }
    }
  }

  .content-list {
    padding: 20rpx;

    .loading-container {
      display: flex;
      flex-direction: column;
      align-items: center;
      padding: 80rpx 0;

      .loading-spinner {
        width: 160rpx;
        height: 160rpx;
        margin-bottom: 20rpx;
        border: 4rpx solid #999999;
        border-top-color: transparent;
        border-radius: 50%;
        animation: spin 1s linear infinite;
      }

      .loading-text {
        font-size: 28rpx;
        color: #999999;
      }

      @keyframes spin {
        0% {
          transform: rotate(0deg);
        }
        100% {
          transform: rotate(360deg);
        }
      }
    }

    .content-item {
      background-color: #ffffff;
      border-radius: 12rpx;
      padding: 24rpx;
      margin-bottom: 24rpx;
      box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);

      .item-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 16rpx;

        .user-info {
          display: flex;
          align-items: center;

          .avatar {
            width: 80rpx;
            height: 80rpx;
            border-radius: 40rpx;
            margin-right: 16rpx;
          }

          .user-details {
            display: flex;
            flex-direction: column;

            .username {
              font-size: 28rpx;
              font-weight: 500;
              color: $text-color;
              margin-bottom: 4rpx;
            }

            .time {
              font-size: 24rpx;
              color: #999999;
            }
          }
        }

        .content-tag {
          font-size: 24rpx;
          padding: 4rpx 12rpx;
          border-radius: 4rpx;

          &.tag-post {
            background-color: #e6f7ff;
            color: #1890ff;
          }

          &.tag-comment {
            background-color: #f6ffed;
            color: #52c41a;
          }

          &.tag-reply {
            background-color: #fff7e6;
            color: #fa8c16;
          }
        }
      }

      .item-content {
        margin-bottom: 20rpx;

        .content-text {
          font-size: 28rpx;
          color: $text-color;
          line-height: 1.6;
          margin-bottom: 16rpx;
        }

        .image-container {
          display: flex;
          flex-wrap: wrap;

          .content-image {
            width: 200rpx;
            height: 200rpx;
            margin-right: 12rpx;
            margin-bottom: 12rpx;
            border-radius: 8rpx;
          }
        }
      }

      .item-footer {
        .report-reason {
          background-color: #fff7e6;
          padding: 16rpx;
          border-radius: 8rpx;
          margin-bottom: 20rpx;
          position: relative;

          .reason-label {
            font-size: 26rpx;
            color: #fa8c16;
            font-weight: 500;
          }

          .reason-text {
            font-size: 26rpx;
            color: #666666;
          }

          .reports-count {
            position: absolute;
            right: 16rpx;
            top: 16rpx;
            font-size: 24rpx;
            color: $danger-color;
          }
        }

        .review-actions {
          display: flex;
          justify-content: flex-end;

          .action-button {
            margin-left: 20rpx;
            font-size: 26rpx;
            padding: 0 30rpx;
            height: 64rpx;
            line-height: 64rpx;
            border-radius: 32rpx;

            &.approve {
              background-color: $success-color;
              color: #ffffff;
            }

            &.reject {
              background-color: $danger-color;
              color: #ffffff;
            }

            &.ignore {
              background-color: #f7f7f7;
              color: #666666;
            }

            &::after {
              border: none;
            }
          }
        }
      }
    }

    .empty-list {
      display: flex;
      flex-direction: column;
      align-items: center;
      padding: 80rpx 0;

      .empty-icon {
        width: 160rpx;
        height: 160rpx;
        margin-bottom: 20rpx;
        opacity: 0.5;
      }

      .empty-text {
        font-size: 28rpx;
        color: #999999;
      }

      .empty-description {
        font-size: 24rpx;
        color: #999999;
        margin-top: 16rpx;
      }
    }
  }
}
</style>
